package cn.kgc.springboot06.redis;

import cn.kgc.springboot06.utils.ApplicationContextUtils;
import org.apache.ibatis.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.DigestUtils;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/3/28
 * @Description:  redis缓存
 */
public class RedisCache implements Cache {

    private final String id;

    public RedisCache(String id){
        this.id = id;
    }

    //获取命名空间
    @Override
    public String getId() {
        return id;
    }

    // 设置缓存数据   redis
    @Override
    public void putObject(Object key, Object value) {
        //如何将数据缓存到redis
        RedisTemplate redisTemplate = getRedisTemplate();
        // 通过hash算法 减少key的长度
        String s = DigestUtils.md5DigestAsHex(key.toString().getBytes());
        redisTemplate.opsForHash().put(id, s, value);

    }


    // 获取缓存数据  hit  hash  MD5
    @Override
    public Object getObject(Object key) {
        RedisTemplate redisTemplate = getRedisTemplate();
        String s = DigestUtils.md5DigestAsHex(key.toString().getBytes());
        Object o = redisTemplate.opsForHash().get(id, s);
        return o ;
    }

    // 默认没有使用该方法
    @Override
    public Object removeObject(Object key) {
        return null;
    }

    // 清空缓存
    @Override
    public void clear() {

        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.delete(id);
    }

    // 获取缓存数据的个数
    @Override
    public int getSize() {
        RedisTemplate redisTemplate = getRedisTemplate();
        int i = redisTemplate.opsForHash().size(id).intValue();
        return i;
    }


    private RedisTemplate getRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
        // 设置redis中key的类型 String
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return  redisTemplate;
    }
}
